package controllers

import (
	"nway_dsr/dsr/libs"
	"nway_dsr/dsr/models"
	"strings"
	"time"
)

type AdminController struct {
	BaseController
}

func (self *AdminController) Admin() {
	self.Data["pageTitle"] = "用户管理"
	self.display()
}

func (self *AdminController) Add() {
	self.Data["pageTitle"] = "添加账号"
	self.display()
}

// 保存账号
func (self *AdminController) AjaxSave() {
	admin := new(models.DsrUser)

	admin.Account = self.GetString("login_name")
	admin.Name = self.GetString("real_name")
	_, err := models.AdminGetByName(admin.Account)
	if err == nil {
		self.ajaxMsg("登录名已经存在", MSG_ERR)
	}
	pwd, salt := libs.Password(4, "")
	admin.Password = pwd
	admin.Salt = salt
	admin.CreateTime = time.Now().Unix()

	_, err = models.AdminAdd(admin)
	if err != nil {
		self.ajaxMsg(err, MSG_ERR)
	}
	self.ajaxMsg("添加成功", 0)
}

// 账号列表
func (self *AdminController) ContentTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//查询条件
	filters := make([]interface{}, 0)
	result, count := models.AdminGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["account"] = v.Account
		row["password"] = v.Password
		row["name"] = v.Name
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

// 账号列表
func (self *AdminController) AjaxDel() {

	user_id, _ := self.GetInt64("id")
	admin, _ := models.AdminGetById(user_id)

	if err := admin.Delete(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("删除成功", 0)
}

func (self *AdminController) Edit() {
	self.Data["id"], _ = self.GetInt64("id")
	self.display()
}

// 改密码
func (self *AdminController) UpdateSave() {
	self.ajaxMsg("禁止修改", MSG_ERR)
	id, _ := self.GetInt64("id")
	admin, err := models.AdminGetById(id)

	admin.Id = id

	admin.Account = self.GetString("login_name")
	admin.Name = self.GetString("real_name")
	oldPassword := self.GetString("password_old")
	passwordNew1 := self.GetString("password_new1")
	passwordNew2 := self.GetString("password_new2")
	resetPwd := self.GetString("reset_pwd")

	if resetPwd == "1" {
		pwdOld := strings.TrimSpace(oldPassword)           //去空格
		pwdOldMd5 := libs.Md5([]byte(pwdOld + admin.Salt)) //解密
		if pwdOldMd5 != admin.Password {
			self.ajaxMsg("旧密码输入错误", MSG_ERR)
		}
		if passwordNew1 != passwordNew2 {
			self.ajaxMsg("两次密码不相同", MSG_ERR)
		}
		pwd, salt := libs.Password(4, passwordNew1)
		admin.Password = pwd
		admin.Salt = salt
	}

	err = admin.Update()
	if err != nil {
		self.ajaxMsg(err, MSG_ERR)
	}
	self.ajaxMsg("修改成功", 0)
}
